package com.app.baselibrary.base

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.app.baselibrary.delegate.LifecycleComponent
import com.app.baselibrary.delegate.lifecycleComponent
import java.util.concurrent.atomic.AtomicBoolean

/**
 * Fragment 基类
 */
abstract class BaseFragment<V : ViewBinding> : Fragment(), LifecycleComponent<V> by lifecycleComponent() {

    private val load = AtomicBoolean(false)


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        bind(this)
        return requireViewBinding().root
    }

    open fun onLazyLoad(){

    }
    override fun onResume() {
        super.onResume()
        if (openLazy() && !load.get()){
            load.set(true)
            onLazyLoad()
            return
        }
    }

    /**
     * 是否开启懒加载
     */
    open fun openLazy(): Boolean = true


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        childFragmentManager.fragments.forEach { it.onRequestPermissionsResult(
            requestCode,
            permissions,
            grantResults
        ) }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        childFragmentManager.fragments.forEach { it.onActivityResult(requestCode, resultCode, data) }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        view?.let { unbindDrawables(it) }
    }

    private fun unbindDrawables(view: View) {
        if (view.background != null) {
            view.background.callback = null
        }
        if (view is ViewGroup && view !is AdapterView<*>) {
            for (i in 0 until view.childCount) {
                unbindDrawables(view.getChildAt(i))
            }
            view.removeAllViews()
        }
    }

    /**
     * 显示空布局或者网络异常布局
     */
    fun setShowEmpty(textView: TextView, content: String, resId: Int){
        textView.visibility = View.VISIBLE
        val drawable =resources.getDrawable(resId)
        drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
        textView.setCompoundDrawables(null, drawable, null, null)
        textView.text=content
    }
}